package cn.zbzcode.hrm.service.impl;

import cn.zbzcode.hrm.domain.Employee;
import cn.zbzcode.hrm.domain.Meal;
import cn.zbzcode.hrm.domain.Tenant;
import cn.zbzcode.hrm.dto.TenantEnteringDto;
import cn.zbzcode.hrm.mapper.EmployeeMapper;
import cn.zbzcode.hrm.mapper.TenantMapper;
import cn.zbzcode.hrm.service.ITenantService;
import cn.zbzcode.hrm.utils.encrypt.MD5;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zbz
 * @since 2020-04-20
 */
@Service
@Transactional
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private EmployeeMapper employeeMapper ;

    @Override
    public void entering(TenantEnteringDto dto) {
        //1.参数做基本判断
        if(StringUtils.isEmpty(dto.getTenant().getCompanyName())){
            throw new RuntimeException("无效的公司名字");
        }
        if(StringUtils.isEmpty(dto.getEmployee().getUsername())){
            throw new RuntimeException("无效的账号");
        }

        //2.保存机构表
        Tenant tenant = dto.getTenant();
        tenant.setRegisterTime(new Date());
        tenant.setAddress(tenant.getAddress());
        tenant.setCompanyName(tenant.getCompanyName());
        tenant.setCompanyNum(tenant.getCompanyNum());
        tenant.setLogo(tenant.getLogo());
        tenant.setTenantType(tenant.getTenantType());
        tenant.setState(Tenant.STATE_NORMAL);  //机构可用
        baseMapper.insert(tenant);

        //3.保存员工表-机构的超管账号

        Employee employee = dto.getEmployee();
        //密码加密
        String enPass = MD5.getMD5(employee.getPassword() + "zbzcode");
        employee.setPassword(enPass);
        employee.setEmail(employee.getEmail());
        employee.setTel(employee.getTel());
        employee.setUsername(employee.getUsername());
        employee.setInputTime(new Date());
        employee.setState(Employee.STATE_NORMAL);
        employee.setTenantId(tenant.getId());
        employee.setType(Employee.TYPE_MANAGER);
        employeeMapper.insert(employee);

        //4.保存机构和套餐的中间表
        Date expireDate = DateUtils.addDays(new Date() , 7);
        baseMapper.insertRelationWithMeal(dto.getMealId() , tenant.getId(),expireDate, Meal.STATE_NO_PAY);
    }
}
